package com.ljy.jymail.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljy.common.utils.HttpUtils;
import com.ljy.common.utils.R;
import com.ljy.common.vo.SocialUser;
import com.ljy.jymail.member.dao.MemberLevelDao;
import com.ljy.jymail.member.entity.MemberLevelEntity;
import com.ljy.jymail.member.exeception.PhoneExistException;
import com.ljy.jymail.member.exeception.UserNameExistException;
import com.ljy.jymail.member.vo.MemberLoginVo;
import com.ljy.jymail.member.vo.MemberRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.common.utils.PageUtils;
import com.ljy.common.utils.Query;

import com.ljy.jymail.member.dao.MemberDao;
import com.ljy.jymail.member.entity.MemberEntity;
import com.ljy.jymail.member.service.MemberService;
import org.springframework.transaction.annotation.Transactional;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }


    /*
     * 会员注册功能
     *
     * */
    @Override
    @Transactional
    public void register(MemberRegisterVo vo) {
        MemberEntity entity = new MemberEntity();
        MemberDao dao = this.baseMapper;


        //设置会员等级Id
        //获取默认会员等级Id
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //设置:

        //设置前需要检查用户名和手机号是否唯一,为了让Controller能感知异常,故使用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());

        //设置密码:需要进行MD5和盐值加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他的默认信息

        //保存  吧
        dao.insert(entity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer integer = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (integer > 0) {
            throw new PhoneExistException();
        }
    }


    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer integer = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (integer > 0) {
            throw new UserNameExistException();
        }
    }


    /*用户登录方法*/
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String password = vo.getPassword();

        String loginacct = vo.getLoginacct();

        //1-去数据库根据手机号或者用户名查询用户是否存在
        MemberDao dao = this.baseMapper;
        //用户名或者手机号匹配
        MemberEntity entity = dao.selectOne(new QueryWrapper<MemberEntity>().
                eq("username", loginacct).
                or().eq("mobile", loginacct));
        if (entity == null) {
            //登录失败
            return null;
        } else {
            //获取到数据库的password,与页面进行对比
            //数据库盐值加密后密码的解析
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = encoder.matches(password, entity.getPassword());
            if (matches) {
                //登录成功
                return entity;
            } else {
                //登陆失败
                return null;
            }

        }

    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //社交登录，登陆与注册合并逻辑
        String uid = socialUser.getUid();
        //1、判断当前社交用户是否已经登陆过-->查看数据库中是否已经存在输入的uid
        MemberDao dao = this.baseMapper;
        MemberEntity memberEntity = dao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            dao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {

            MemberEntity register = new MemberEntity();
            try {
                //没有对应的记录就该注册一个
                register = new MemberEntity();
                //查询当前社交用户的社交账号信息(昵称，性别等)
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity(), "UTF-8");
                    JSONObject jsonObject = JSON.parseObject(json);
                    //微博昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    //头像
                    String profileImageUrl = jsonObject.getString("profile_image_url");

                    //...

                    //注册
                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                    register.setHeader(profileImageUrl);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());
            dao.insert(register);

            return register;
        }


    }

}